Removing expired certificates

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
$servers = (Get-AdComputer -Filter * -SearchBase 'dc=domain,dc=local').DNSHostName
$cred = (Get-Credential)
foreach ($server in $servers)
{
  $session = New-PSSession -ComputerName $server -Credential $cred
  Invoke-Command -Session $session -ScriptBlock {
    Write-Output -InputObject $env:COMPUTERNAME
    $certsMy = Get-ChildItem -Path Cert:\LocalMachine\My |
    Where-Object -Property notafter -LT -Value (Get-Date) |
    Select-Object -ExpandProperty Thumbprint
    foreach ($cert in $certsMy)
    {
      Remove-Item -Path cert:\LocalMachine\My\$cert
    }
  }
  Remove-PSSession $session
}